//
//  HHDotImageView.m
//  XueZhiYun
//
//  Created by chun.chen on 2018/8/10.
//  Copyright © 2018年 Zhihan. All rights reserved.
//  红点view

#import "HHDotImageView.h"
#import <BCFoundation/BCFoundationUtils.h>
#import <BCFoundation/UIColor+BCHelper.h>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#import <Masonry/Masonry.h>
#pragma clang diagnostic pop
#import <BCComConfigKit/BCComConfig.h>

@interface HHDotImageView ()

@property (nonatomic, strong) UIImage *image;

@end

@implementation HHDotImageView

#pragma mark - system
- (instancetype)initWithImage:(nullable UIImage *)image {
    self = [super initWithFrame:CGRectMake(0, 0, MAX(image.size.width + 3, 44), MAX(image.size.height + 3, 44))];
    if (self) {
        _image = image;
        [self configureSubviews];
    }
    return self;
}

- (CGSize)intrinsicContentSize {
    return CGSizeMake(44, 44);
}

- (void)dealloc {
    BCLogDealloc();
}

#pragma mark - SubViews
- (void)configureSubviews {
    self.userInteractionEnabled = YES;

    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
    [self addGestureRecognizer:gesture];

    self.imageView = [[UIImageView alloc] initWithImage:_image];
    self.dotImgView = [[UIImageView alloc] init];
    self.dotImgView.layer.cornerRadius = 3;
    self.dotImgView.backgroundColor = UIColor.redColor;

    [self addSubview:self.imageView];
    [self addSubview:self.dotImgView];

    [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self);
        make.centerY.mas_equalTo(self);
        make.size.mas_equalTo(self.image.size);
    }];
    [_dotImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.imageView.mas_top).offset(3);
        make.left.mas_equalTo(self.imageView.mas_right).offset(-3);
        make.size.mas_equalTo(CGSizeMake(6, 6));
    }];
}

- (void)handleActionForTapGesture:(UITapGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateRecognized) {
        if (self.clickBlock) {
            self.clickBlock(self);
        }
    }
}

#pragma mark - public
- (void)updateDoteOffset:(CGPoint)offset {
    if (!self.dotImgView.superview) {
        return;
    }
    [self.dotImgView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.imageView.mas_top).offset(offset.y);
        make.left.mas_equalTo(self.imageView.mas_right).offset(offset.x);
    }];
}

@end
